package com.css.chat.logic.login;

import com.css.chat.base.Constants;
import com.css.chat.base.SessionManager;
import com.css.chat.base.UiBaseService;
import com.css.chat.logic.login.message.req.ReqHeartBeat;
import com.css.chat.logic.login.message.req.ReqUserLogin;
import com.css.chat.logic.login.message.res.ResUserLogin;
import com.css.chat.ui.R;
import com.css.chat.ui.StageController;
import com.css.chat.util.I18n;
import com.css.chat.util.enums.SchedulerManager;
import javafx.scene.control.Label;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author zyj
 * @description
 * @date 2019/7/22 16:33
 **/
public class LoginManager {

    Logger logger = LoggerFactory.getLogger(this.getClass());
    private static LoginManager instance = new  LoginManager();

    private LoginManager() {}

    public static LoginManager getInstance() {
        return instance;
    }

    public void beginToLogin(long userId, String password) {
        ReqUserLogin reqLogin= new ReqUserLogin();
        reqLogin.setUserId(userId);
        reqLogin.setUserPwd(password);

        System.out.println("向服务端发送登录请求");

        SessionManager.INSTANCE.sendMessage(reqLogin);
    }

    public void handleLoginResponse(ResUserLogin resp) {
        boolean isSucc = resp.getIsValid() == Constants.TRUE;
        if (isSucc) {
            UiBaseService.INSTANCE.runTaskInFxThread(() -> {
                System.out.println("===============>>>>>登陆成功");
                redirecToMainPanel();
            });

            registerHeartTimer();
        }else {
            UiBaseService.INSTANCE.runTaskInFxThread(() -> {
                StageController stageController = UiBaseService.INSTANCE.getStageController();
                Stage stage = stageController.getStageBy(R.id.LoginView);
                Pane errPane = (Pane)stage.getScene().getRoot().lookup("#errorPane");
                errPane.setVisible(true);
                Label errTips = (Label)stage.getScene().getRoot().lookup("#errorTips");
                errTips.setText(I18n.get("login.operateFailed"));
            });
        }
    }

    /**
     * 注册心跳事件
     */
    private void registerHeartTimer() {
        logger.info("添加心跳包");
        SchedulerManager.INSTANCE.scheduleAtFixedRate("HEART_BEAT", () -> {
            SessionManager.INSTANCE.sendMessage(new ReqHeartBeat());
        }, 0, 5*1000);
    }

    /**
     * 跳转页面
     * @author zyj
     * @date 2019/7/25 14:20
     */
    private void redirecToMainPanel() {
        StageController stageController = UiBaseService.INSTANCE.getStageController();
        stageController.switchStage(R.id.MainView, R.id.LoginView);
    }

}
